#
#  Copyright (c) 2020 NetEase Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

#!/bin/bash

# curve-snapshotcloneserver路径
curveBin=/usr/bin/curve-snapshotcloneserver

# 默认配置文件
confPath=/etc/curve/snapshot_clone_server.conf

# 日志文件路径
logPath=/data/log/curve/snapshotclone

# serverAddr
serverAddr=

# pidfile
pidFile=${HOME}/curve-snapshot.pid

# daemon log
daemonLog=${logPath}/curve-snapshot-daemon.log

# console output
consoleLog=${logPath}/curve-snapshot-console.log

# 启动snapshotcloneserver
function start_server() {
    # 检查daemon
    if ! type daemon &> /dev/null
    then
        echo "No daemon installed"
        exit
    fi

    # 检查curve-snapshotcloneserver
    if [ ! -f ${curveBin} ]
    then
        echo "No curve-snapshotcloneserver installed, Path is ${curveBin}"
        exit
    fi

    # 检查配置文件
    if [ ! -f ${confPath} ]
    then
        echo "Not found snapshot_clone_server.conf, Path is ${confPath}"
        exit
    fi

    # 判断是否已经通过daemon启动了curve-snapshotcloneserver
    daemon --name curve-snapshotcloneserver --pidfile ${pidFile} --running
    if [ $? -eq 0 ]
    then
        echo "Already started curve-snapshotcloneserver by daemon"
        exit
    fi

    # 创建logPath
    mkdir -p ${logPath} > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        echo "Create log path failed: ${logPath}"
        exit
    fi

    # 检查logPath是否有写权限
    if [ ! -w ${logPath} ]
    then
        echo "Write permission denied: ${logPath}"
        exit 1
    fi

    # 检查consoleLog是否可写或者能否创建，初始化glog之前的日志存放在这里
    touch ${consoleLog} > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        echo "Can't Write or Create console log: ${consoleLog}"
        exit
    fi

    # 检查daemonLog是否可写或者是否能够创建
    touch ${daemonLog} > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
        echo "Can't Write or Create daemon logfile: ${daemonLog}"
        exit
    fi

    # 未指定serverAddr, 从配置文件中解析出网段
    if [ -z ${serverAddr} ]
    then
        subnet=`cat $confPath|grep server.subnet|awk -F"=" '{print $2}'`
        port=`cat $confPath|grep server.port|awk -F"=" '{print $2}'`
        prefix=`echo $subnet|awk -F/ '{print $1}'|awk -F. '{printf "%d", ($1*(2^24))+($2*(2^16))+($3*(2^8))+$4}'`
        mod=`echo $subnet|awk -F/ '{print $2}'`
        mask=$((2**32-2**(32-$mod)))
        ip=
        echo "subnet: $subnet"
        echo "port: $port"
        # 对prefix再取一次模，为了支持10.182.26.50/22这种格式
        prefix=$(($prefix&$mask))
        for i in `/sbin/ifconfig -a|grep inet|grep -v inet6|awk '{print $2}'|tr -d "addr:"`
        do
                # 把ip转换成整数
                ip_int=`echo $i|awk -F. '{printf "%d\n", ($1*(2^24))+($2*(2^16))+($3*(2^8))+$4}'`
                if [ $(($ip_int&$mask)) -eq $prefix ]
                then
                    ip=$i
                    break
                fi
        done
        if [ -z "$ip" ]
        then
                echo "no ip matched!\n"
                return 1
        fi
        serverAddr=${ip}:${port}
    fi

    daemon --name curve-snapshotcloneserver --core --inherit \
            --respawn --attempts 100 --delay 10 \
            --pidfile ${pidFile} \
            --errlog ${daemonLog} \
            --output ${consoleLog} \
            -- ${curveBin} -conf=${confPath} -addr=${serverAddr} -log_dir=${logPath} -stderrthreshold=3 -graceful_quit_on_sigterm=true

    sleep 1
    show_status
}

# 停止daemon进程和curve-snapshotcloneserver
function stop_server() {
    # 判断是否已经通过daemon启动了curve-snapshotcloneserver
    daemon --name curve-snapshotcloneserver --pidfile ${pidFile} --running
    if [ $? -ne 0 ]
    then
        echo "Didn't start curve-snapshotcloneserver by daemon"
        exit 1
    fi

    daemon --name curve-snapshotcloneserver --pidfile ${pidFile} --stop
    if [ $? -ne 0 ]
    then
        echo "stop may not success!"
    else
        echo "curve-snapshotcloneserver exit success!"
        echo "daemon exit success!"
    fi
}

# restart
function restart_server() {
    # 判断是否已经通过daemon启动了curve-snapshotcloneserver
    daemon --name curve-snapshotcloneserver --pidfile ${pidFile} --running
    if [ $? -ne 0 ]
    then
        echo "Didn't started curve-snapshotcloneserver by daemon"
        exit
    fi

    daemon --restart --name curve-snapshotcloneserver --pidfile ${pidFile}
    if [ $? -ne 0 ]
    then
        echo "Restart failed"
    fi
}

# show status
function show_status() {
    # 判断是否已经通过daemon启动了curve-snapshotcloneserver
    daemon --name curve-snapshotcloneserver --pidfile ${pidFile} --running
    if [ $? -ne 0 ]
    then
        echo "Didn't start curve-snapshotcloneserver by daemon"
        exit 1
    fi

    # 查询leader的IP
    leaderAddr=`tac ${consoleLog}|grep -m 1 -B 1000000 "Logging before InitGoogleLogging()"|grep "leader"|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|head -n1`

    # 如果load configuration之后的日志，没有leader相关日志
    # 那么leaderAddr为空, snapshotcloneserver应该没有起来
    if [ -z ${leaderAddr} ]
    then
        echo "SnapshotClone may not start successfully, check log"
        exit 1
    fi

    if [ ${leaderAddr} = "127.0.0.1" ]
    then
        echo "Current SnapshotClone is LEADER"
    else
        # 查询是否和自身ip相等
        for ip in `(hostname -I)`
        do
            if [ ${leaderAddr} = ${ip} ]
            then
                echo "Current SnapshotClone is LEADER"
                exit
            fi
        done

        echo "Current SnapshotClone is FOLLOWER, LEADER is ${leaderAddr}"
    fi
}

# 使用方式
function usage() {
    echo "Usage:"
    echo "  snapshot-daemon start -- start deamon process and watch on curve-snapshotcloneserver process"
    echo "        [-c|--confPath path]        configuration file"
    echo "        [-l|--logPath  path]        log directory"
    echo "        [-a|--serverAddr  ip:port]  listening address"
    echo "  snapshot-daemon stop  -- stop daemon process and curve-snapshotcloneserver"
    echo "  snapshot-daemon restart -- restart curve-snapshotcloneserver"
    echo "  snapshot-daemon status -- show snapshotcloneserver status [LEADER/STATUS]"
    echo "Examples:"
    echo "  snapshot-daemon start -c /etc/curve/snapshot_clone_server.conf -l ${HOME}/ -a 127.0.0.1:5555"
}

# 检查参数启动参数，最少1个
if [ $# -lt 1 ]
then
    usage
    exit
fi

case $1 in
"start")
    shift # pass first argument

    # 解析参数
    while [[ $# -gt 1 ]]
    do
        key=$1

        case $key in
        -c|--confPath)
            confPath=`realpath $2`
            shift # pass key
            shift # pass value
            ;;
        -a|--serverAddr)
            serverAddr=$2
            shift # pass key
            shift # pass value
            ;;
        -l|--logPath)
            logPath=`realpath $2`
            shift # pass key
            shift # pass value
            ;;
        *)
            usage
            exit
            ;;
        esac
    done

    start_server
    ;;
"stop")
    stop_server
    ;;
"restart")
    restart_server
    ;;
"status")
  show_status
  ;;
*)
    usage
    ;;
esac
